package com.obrempon.credit.market.ui.activity

import android.os.Handler
import android.os.Looper
import android.view.View
import com.obrempon.credit.market.R
import com.obrempon.credit.market.common.CommonActivity
import com.obrempon.credit.market.configs.ObremponApiPath
import com.obrempon.credit.market.configs.ObremponApiUrl
import com.obrempon.credit.market.configs.ObremponApiUrl.addCommonParams
import com.obrempon.credit.market.databinding.ObremponUserSettingActBinding
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.ui.dialog.ObremponUserDataClearDialog
import com.obrempon.credit.market.utils.ObremponTitleBarUtil
import com.obrempon.credit.market.utils.helper.ObremponConfigsHelper
import com.obrempon.credit.market.utils.helper.ObremponProductHelper
import com.obrempon.credit.market.utils.shared.ObremponSharedHelper
import com.obrempon.module.shapeview.drawable.ShapeGradientOrientation
import org.json.JSONObject

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/27 16:16
 * @Annotation：设置
 */
class ObremponSettingAct: CommonActivity() {
    lateinit var binding: ObremponUserSettingActBinding
    private var deleteDataAfterDate = ""

    override fun takeObremponRootView(): View {
        binding = ObremponUserSettingActBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        setObremponTitleBarVisibility(View.VISIBLE)
        setObremponTextTitle(getString(R.string.obrempon_user_center_setting))
        setObremponTextTitleColor(getColor(R.color.black))
        setObremponRightBtnRes(R.mipmap.obrempon_customer_icon)
        setObremponBackBtnRes(R.mipmap.obrempon_back_icon)
        ObremponTitleBarUtil.setStatusBarLightMode(this, true)
        setObremponTitleBarVisibility(View.VISIBLE)
        rootViewBinding.rootLayout.shapeDrawableBuilder
            .setSolidGradientColors(getColor(R.color.color_ffcbe0ff),getColor(R.color.white),getColor(R.color.white))
            .setSolidGradientOrientation(ShapeGradientOrientation.TOP_TO_BOTTOM)
            .intoBackground()
    }

    override fun initObremponListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Setting Page")
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER,"Setting Page")
        }

        //清空用户数据
        binding.buttonDeleteData.setOnClickListener {
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_DATA_CLEAR)
            val pList = ObremponProductHelper.takeObremponUncompleteProductList()
            //存在未结清的账单
            if (pList.size > 0){
                showErrorTipsDialog(getString(R.string.obrempon_user_data_clear_error),"Setting Page")
                return@setOnClickListener
            }
            showUserClearDataDialog()
        }

        //退出登录
        binding.buttonSignOut.setOnClickListener {
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_LOGINOUT)
            //退出登录，需要移除用户保存的信息
            ObremponSharedHelper.onObremponLoginOut()
            Handler(Looper.getMainLooper()).postDelayed({
                onIntent(ObremponLoginAct::class.java)
            },300)
        }
    }

    override fun takeObremponData() {
        //获取版本名称
        val packageInfo = packageManager.getPackageInfo(this.packageName, 0)
        binding.textAppVersion.text = String.format(getString(R.string.obrempon_user_setting_version),packageInfo.versionName)

        binding.buttonDeleteData.visibility = View.INVISIBLE
        //需要判断是否需要显示删除用户数据按钮
        submitObremponUserClearDataAction(true)
    }

    /**
     * 清空用户数据dialog
     */
    private fun showUserClearDataDialog(){
        val clearDialog = ObremponUserDataClearDialog(this,object : ObremponUserDataClearDialog.IDialogCallback{
            override fun onUserDataClearConfirmClick() {
                submitObremponUserClearDataAction(false)
            }
        })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
        clearDialog.showObremponDeletePersonalDataDesc(ObremponConfigsHelper.takeObremponDeletePersonalDataDesc(),deleteDataAfterDate)
    }

    /**
     * 清除用户数据 或 获取是否显示删除数据按钮
     */
    private fun submitObremponUserClearDataAction(isShowDeleteButton: Boolean){
        showObremponLoading()
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_USER_DATA_CLEAR_PATH)
        }
        if (isShowDeleteButton){
            params.put("type","GET")
        } else {
            params.put("type","DROP")
        }
        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                if (isShowDeleteButton){
                    val obj = data.optJSONObject("obj")
                    if (obj != null && obj.has("showDropButton") && obj.optString("showDropButton") == "YES"){
                        binding.buttonDeleteData.visibility = View.VISIBLE
                        deleteDataAfterDate = obj.optString("againDate")
                    } else {
                        binding.buttonDeleteData.visibility = View.INVISIBLE
                    }
                } else {
                    hideObremponLoading()
                    //退出登录，需要移除用户保存的信息
                    ObremponSharedHelper.onObremponLoginOut()
                    onIntent(ObremponLoginAct::class.java)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showObremponToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_USER_SETTING_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_USER_SETTING_END)
    }
}